<?php

class openapi_api_function_v1_salesman extends openapi_api_function_abstract implements openapi_api_function_interface{

	
	public function apply($params,&$code,&$sub_msg)
	{
		$member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $currMember = $this->get_current_member();
        if($currMember['seller']=='seller'){
            return $this->apiData(false,null,400,app::get('b2c')->_('经销商不能申请成为促销员'));
        }
		$store_name = $params['store_name'];
        $store_account = app::get('pam')->model('account')->getRow('account_id',array('login_name'=>$store_name));
        if(empty($store_account)){
            return $this->apiData(false,null,400,app::get('b2c')->_('经销商不存在！'));
        }
        $store = app::get('business')->model('storemanger')->getRow('*',array('account_id'=>$store_account['account_id']));
        if(empty($store)){
            return $this->apiData(false,null,400,app::get('b2c')->_('所填非经销商！'));
        }
        $mystore = app::get('business')->model('salesman')->getList("*",array('member_id'=>$member_id,'status'=>'1'));
        if(!empty($mystore)){
            return $this->apiData(false,null,400,app::get('b2c')->_('您已是在职促销员，不可重复申请'));
        }
        $myapply = app::get('business')->model('salesman')->getList("*",array('member_id'=>$member_id,'store_id'=>$store['store_id'],'status|in'=>array('0','1','3')));
        if(!empty($myapply)){
            return $this->apiData(false,null,400,app::get('b2c')->_('您已提交过申请，请等待审核！'));
        }
        $remark = $params['remark'];
        $saler['name'] = $currMember['name'];
        $saler['store_id'] = $store['store_id'];
        $saler['member_id'] = $member_id;
        $saler['remark'] = $params['remark'];
        $saler['apply_time'] = time();
        if(app::get('business')->model('salesman')->save($saler)){
            //发送站内信
            $data['to_id'] = $store_account['account_id'];
            $data['msg_to'] = $store_account['login_name'];
            $data['subject'] = app::get('b2c')->_("促销员申请");
            $data['comment'] = app::get('b2c')->_($currMember['uname']."申请成为促销员");
            $data['has_sent'] = 'true';
            $data['deal_type'] = '1';
            $data['member_id'] = $member_id;
            $data['uname'] = $currMember['uname'];
            kernel::single('b2c_message_msg')->send($data);
            return $this->apiData(true,null,200,app::get('b2c')->_('申请提交成功！'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('申请提交失败！'));
        }
	}

    
    public function apply_logs($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = 10;
        $mdl_salesman = app::get('business')->model('salesman');
        $mdl_storemanger = app::get('business')->model('storemanger');
        $salesman = $mdl_salesman->getList('*',array('member_id'=>$member_id));

        if(!empty($salesman)){
            foreach ($salesman as $key => $value) {
                $store = $mdl_storemanger->getRow('store_name',array('store_id'=>$value['store_id']));
                $salesman[$key]['store_name'] = $store['store_name'];
            }
        }
        return $this->apiData(true,$salesman,200);
    }

    
    public function apply_quit($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $mdl_salesman = app::get('business')->model('salesman');
        $salesman = $mdl_salesman->getRow('*',array('seller_id'=>$params['seller_id']));
        if($salesman['member_id'] != $member_id){
            return $this->apiData(failed,null,400,app::get('b2c')->_('参数提交错误！！'));
        }
        $salesman['quit_reasion'] = $params['quit_reasion'];
        $salesman['quit_apply_time'] = time();
        $salesman['status'] = 3;//3:申请退出 4:已退出
        if($mdl_salesman->save($salesman)){
            return $this->apiData(true,null,200,app::get('b2c')->_('申请提交成功！'));
        }else{
            return $this->apiData(failed,null,400,app::get('b2c')->_('申请提交失败！'));
        }
    }

	
	public function scancode($params,&$code,&$sub_msg)
	{
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
		$mdl_goods_codelog = app::get('b2c')->model('goods_codelog');
        $mdl_salesman = app::get('business')->model('salesman');
        $mdl_sales_rebate  = app::get('b2c')->model('sales_rebate');
        $mdl_sales_rebate_log  = app::get('b2c')->model('sales_rebate_log');
        $mdl_sales_goods_log  = app::get('b2c')->model('sales_goods_log');
        $mdl_goods_store = app::get('b2c')->model('goods_store');
        $mdl_storemanger = app::get('business')->model('storemanger');
        $mdl_members = app::get('b2c')->model('members');
        $barcode = $params['barcode'];
        if($mdl_sales_rebate_log->count(array('barcode'=>$barcode))>0){
            $msg = '该流水码已经扫描过不能重复扫描！';
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }

        $start_barcode = substr($barcode, 0,6);
        $end_barcode = substr($barcode, -7);
        $sql = "select product_id from " . DB_PREFIX . "b2c_goods_codelog where start_code like '{$start_barcode}%' and substr(start_code, -7)<={$end_barcode} and substr(end_code,-7)>={$end_barcode}";
        $codelog = $mdl_goods_codelog->db->select($sql);
        if(empty($codelog)){
            $msg = '流水码错误';
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        $product_id  = $codelog[0]['product_id']; //找到对应的货品
        $saleman = $mdl_salesman->getRow('store_id',array('member_id'=>$member_id, 'status'=>'1'));
        if(empty($saleman)){
            return $this->apiData(false,null,400,app::get('b2c')->_('请先申请成为促销员'));
        }
        $super_store_id = $store_id = $saleman['store_id']; //找到对应的经销商
        $now = time();
        do{
            $s = $mdl_storemanger->getRow('parent_id,store_id',array('store_id'=>$store_id));
            if(empty($s)){
                $msg = '经销商不存在';
                return $this->apiData(false,null,400,app::get('b2c')->_($msg));
            }
            if($s['parent_id']==='0'){
                break;
            }else{
                $sup_ids[]=$s['store_id'];
                $store_id = $s['parent_id'];
            }
        }while(true);
        $rebate_money = 0;
        $has_rebate = false;
        $rebate_detail = array();
        $mdl_store = app::get('business')->model('storemanger');
        foreach ($sup_ids as $key => $value) {
            $rebate_rule = $mdl_sales_rebate->getRow('*',array('store_id'=>$value,'pid'=>$product_id));
            $is_allow = ($rebate_rule['status'] =='true')&&($rebate_rule['remainnums']>0)&&($rebate_rule['start_time']<=$now)&&($rebate_rule['end_time']>=$now);
            if($is_allow){
                $store = $mdl_store->getRow('store_name',array('store_id'=>$rebate_rule['store_id']));
                $rebate_rule['store_name'] = $store['store_name'];
                $rebate_detail[] = $rebate_rule;
                $rebate_money += $rebate_rule['rebate_money'];
                $has_rebate = true;
            }
        }
        $parent_rebate = app::get('b2c')->model('sales_rebate')->getRow('*',array('pid'=>$product_id,'store_id'=>$saleman['store_id'],'status'=>'true','remainnums|than'=>0,'start_time|sthan'=>$now,'end_time|bthan'=>$now));
        $product = app::get('b2c')->model('products')->getRow("name,goods_id,spec_info",array('product_id'=>$product_id));
        $goods = app::get('b2c')->model('goods')->getRow('image_default_id',array('goods_id'=>$product['goods_id']));
        $result['nums'] = $parent_rebate['nums'];
        $result['name'] = $product['name'];
        $result['spec_info'] = $product['spec_info'];
        $result['pic_url'] = base_storager::image_path($goods['image_default_id'],'m');
        $result['rebate_money'] = $rebate_money;
        $result['rebate_detail'] = $rebate_detail;
        if(!$has_rebate){
            return $this->apiData(false,$result,400,app::get('b2c')->_('该商品暂无返利活动'));
        }
        return $this->apiData(true,$result,200);
	}

    
    public function dosales_rebate($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->dosales_rebate($params,$aData,$msg);
        if($res){
            return $this->apiData(true,null,200,$msg);
        }else{
            return $this->apiData(false,null,400,$msg);
        }
    }

    
    public function do_salesman_approve($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $data['seller_id'] = $params['seller_id'];
        $data['reason'] = $params['reason'];
        $data['status'] = $params['status'];
        $data['approve_time'] = time();
        $mdl_salesman = app::get('business')->model('salesman');
        if($mdl_salesman->save($data)){
            return $this->apiData(true,null,200,app::get('business')->_('审核完成'));
        }else{
            return $this->apiData(false,null,400,app::get('business')->_('审核失败'));
        }
    }

    
    public function confirm_quit($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $storeinfo = app::get('business')->model('storemanger')->getRow('*',array('account_id'=>$member_id));
        $mdl_salesman = app::get('business')->model('salesman');
        $salesman = $mdl_salesman->getRow('*',array('seller_id'=>$params['seller_id']));
        if($salesman['store_id']!=$storeinfo['store_id'] || $salesman['status']!='3'){
            return $this->apiData(false,null,400,app::get('b2c')->_('参数错误'));
        }
        $salesman['status'] = 4;
        $salesman['quit_time'] = time();
        if($mdl_salesman->save($salesman)){
            return $this->apiData(true,null,200,app::get('b2c')->_('确认成功'));
        }
        return $this->apiData(false,null,400,app::get()->_('确认失败'));
    }

    
    public function salesmanlist($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $store_info['store_id'];
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;
        $filter = array();
        if($params['status']){
            $filter['status'] = $params['status'];
        }
        $filter['store_id'] = $store_id;
        $salesmanlist = app::get('business')->model('salesman')->getList('*',$filter,($npage-1)*$pagesize,$pagesize);
        if(empty($salesmanlist)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有更多了'));
        }
        $mAccount = app::get('pam')->model('account');
        foreach ($salesmanlist as $key => &$man) {
            $man['name'] = $mAccount->get_operactor_name($man['member_id']);;
        }
        return $this->apiData(true,$salesmanlist,200);
    }

    
    public function rebate_list($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;
        if(!kernel::single('business_salesman_log',$member_id)->rebate_detail($params,$logs,$msg,$npage,$pagesize)){
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        return $this->apiData(true,$logs,200);
    }

    
    public function sales_goods_log($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;
        if(!kernel::single('business_salesman_log',$member_id)->get_sales_goods_log($params,$logs,$msg,$npage,$pagesize)){
            return $this->apiData(false,null,400,app::get('b2c')->_($msg));
        }
        return $this->apiData(true,$logs,200);
    }

    
    public function my_rebate_list($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;
        $logs = app::get('b2c')->model('sales_rebate_log')->getList('*',array('member_id'=>$member_id),($npage-1)*$pagesize,$pagesize,"log_time desc");
        $mProduct = app::get('b2c')->model('products');
        $mGoods = app::get('b2c')->model('goods');
        $mStore = app::get('business')->model('storemanger');
        foreach ($logs as $k => &$log) {
            $p = $mProduct->getRow('goods_id,bn,name,spec_info',array('product_id'=>$log['product_id']));
            $log['name'] = $p['name'].$p['spec_info'];
            $log['bn'] = $p['bn'];
            $store = $mStore->getRow('store_name',array('store_id'=>$log['store_id']));
            $log['store_name'] = $store['store_name'];
        }
        $result['logs'] = array_values($logs);
        $money = app::get('b2c')->model('sales_rebate_log')->getRow('sum(rebate_money) total,count(distinct(barcode)) count',array('member_id'=>$member_id));
        $result['total'] = $money['total'];
        $result['count'] = $money['count'];
        return $this->apiData(true,$result,200);
    }

    
    public function my_rebate_money($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $money = app::get('b2c')->model('sales_rebate_log')->getRow('sum(rebate_money) total,count(distinct(barcode)) count',array('member_id'=>$member_id));
        return $this->apiData(true,$money,200);
    }

    
    public function rebate_rule($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $store_info['store_id'];
        $mdl_products = app::get('b2c')->model('products');
        $db = kernel::database();
        $npage = $params['npage']?$params['npage']:1;
        $pagesize = $params['pagesize']?$params['pagesize']:10;

        $sql = "select p.name,p.product_id,p.spec_info,sg.store_onsale from " . DB_PREFIX . "b2c_goods_store sg join " . DB_PREFIX . "b2c_products p on sg.product_id=p.product_id where sg.store_id={$store_id} and sg.store_onsale>0";
        if($npage==1){
            $result['product'] = $db->select($sql);
        }
        $mdl_sales_rebate = app::get('b2c')->model('sales_rebate');
        $rules = $mdl_sales_rebate->getList('*',array('store_id'=>$store_id),($npage-1)*$pagesize,$pagesize);
        foreach ($rules as $key => $value) {
            $product = $mdl_products->getRow('name,spec_info',array('product_id'=>$value['pid']));
            $rules[$key]['product_name'] = $product['name'];
            $rules[$key]['spec_info'] = $product['spec_info'];
        }
        $result['rules'] = $rules;
        return $this->apiData(true,$result,200);
    }

    
    public function rebate_rule_add($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $store_info['store_id'];
        $currMember = $this->get_current_member();
        $mdl_sales_rebate = app::get('b2c')->model('sales_rebate');
        $mdl_goods_store = app::get('b2c')->model('goods_store');
        $rule = $params;

        if(empty($rule['name'])){
            return $this->apiData(false,'',400,app::get('b2c')->_('规则名称不能为空！'));
        }
        if(empty($rule['rebate_money'])){
            return $this->apiData(false,'',400,app::get('b2c')->_('返利金额不能为空！'));
        }
        if(empty($rule['nums'])){
            return $this->apiData(false,'',400,app::get('b2c')->_('参加规则的货品数量不能为空！'));
        }
        if(!isset($rule['id'])){
            $rs = $mdl_sales_rebate->getRow('id',array('pid'=>$rule['pid'],'status'=>'true'));
            if($rs){
                return $this->apiData(false,'',400,app::get('b2c')->_('该货品已经参加过返利！'));
            }
        }
        $now=time();
        if(!$rule['start_time']||!$rule['end_time']){
            return $this->apiData(false,'',400,app::get('b2c')->_('请填写活动的起始时间'));
        }
        if($rule['end_time']<=$rule['start_time']){
            return $this->apiData(false,'',400,app::get('b2c')->_('开始时间要小于结束时间'));
        }
        if($rule['start_time']<$now){
            return $this->apiData(false,'',400,app::get('b2c')->_('开始时间不能小于当前时间'));
        }
        $store = $mdl_goods_store->getRow('store_onsale,store_freeze',array('store_id'=>$store_id,'product_id'=>$rule['pid']));
        if($rule['nums'] > $store['store_onsale']){
            return $this->apiData(false,'',400,app::get('b2c')->_('参加返利规则的货品的数量不能大于上架库存！'));
        }
        if(md5($params['pay_pwd'])!=$currMember['pay_password']){
            return $this->apiData(false,'',400,app::get('b2c')->_('支付密码输入不正确请重新输入！'));
        }
        $total_price = $rule['rebate_money']*$rule['nums'];
        if($currMember['advance']['total']<$total_price){
            return $this->apiData(false,'',400,app::get('b2c')->_('站内币金额不足，无法添加！'));
        }
        $rule['store_id'] = $store_id;
        $rule['remainnums'] = $rule['nums'];

        if($mdl_sales_rebate->save($rule)){
            //冻结参加返利规则的货品的数量
            $freeze = $store['store_freeze']+$rule['nums'];
            $store_onsale = $store['store_onsale'] - $rule['nums'];
            $product_id = $rule['pid'];
            $store_id = $store_id;
            $ssql = "update " . DB_PREFIX . "b2c_goods_store set store_onsale={$store_onsale},store_freeze={$freeze} where store_id={$store_id} and product_id={$product_id}";
            $mdl_goods_store->db->exec($ssql);

            //冻结经销商的站内币
            $mydata = array(
                    'member_id'=> $currMember['member_id'],
                    'money'=> $total_price,
                    'message'=> app::get('b2c')->_('添加促销员返利规则冻结'),
                    'mtime'=> time(),
                    'memo'=> app::get('b2c')->_('添加促销员返利规则冻结'),
                    'import_money'=> 0,
                    'explode_money'=>$total_price,
                    'member_advance'=>$currMember['advance']['total'] - $total_price,
                );
            if(app::get('b2c')->model('member_advance')->save($mydata)){
                $advance = $currMember['advance']['total'] - $total_price;
                $freeze = $currMember['advance']['freeze']+$total_price;
                $member_id = $currMember['member_id'];
                $sql="update " . DB_PREFIX . "b2c_members set advance={$advance},advance_freeze={$freeze} where member_id={$member_id}";
                app::get('b2c')->model('members')->db->exec($sql);
            }
            return $this->apiData(true,null,200,app::get('b2c')->_('保存成功！'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('保存失败！'));
        }
    }

    
    public function del_rule($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $store_info['store_id'];
        $mdl_sales_rebate = app::get('b2c')->model('sales_rebate');
        $filter = array('id'=>$params['id'],'store_id'=>$store_id);
        $now = time();
        $rule = $mdl_sales_rebate->getRow('*',$filter);
        if(empty($rule)){
            return $this->apiData(false,null,400,app::get('b2c')->_('促销规则不存在'));
        }
        $start_time = $rule['start_time'];
        $end_time = $rule['end_time'];
        if($rule['status']=='true'&&$start_time<=$now&&$end_time>=$now){
            return $this->apiData(false,null,400,app::get('b2c')->_('返利规则正在进行中不允许删除！'));
        }

        if($mdl_sales_rebate->delete($filter))
        {
            return $this->apiData(true,null,200,app::get('b2c')->_('删除成功！'));
        }
        else
        {
            return $this->apiData(false,null,400,app::get('b2c')->_('操作失败'));
        }
    }

    
    public function edit_rule($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store_info = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        $store_id = $store_info['store_id'];
        $rule = app::get('b2c')->model('sales_rebate')->getRow('*',array('id'=>$params['id']));
        if(empty($rule) || $rule['store_id']!=$store_id){
            return $this->apiData(false,null,400,app::get('b2c')->_('该促销规则不存在或无权修改'));
        }
        $rule['status'] = $params['status'];
        if(app::get('b2c')->model('sales_rebate')->save($rule)){
            return $this->apiData(true,null,200,app::get('b2c')->_('修改成功'));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('修改失败'));
        }
    }

}
